package org.paraj.sync;

import java.util.concurrent.CountDownLatch;

public class JobsBarrier{
    CountDownLatch started;
    CountDownLatch finished;
    CountDownLatch startLatch = new CountDownLatch(1);

    public JobsBarrier(int count){
        finished = new CountDownLatch(count);
        started = new CountDownLatch(count);
    }

    public void jobStarted(){
        started.countDown();
        try{
            startLatch.await();
        } catch(InterruptedException e){
            throw new RuntimeException(e);
        }
    }

    public void jobFinished(){
        finished.countDown();
    }

    public void startAndWaitUntilAllJobsFinished(){
        try{
            started.await();
            startLatch.countDown();
            finished.await();
        } catch(InterruptedException e){
            throw new RuntimeException(String.format("Interrupted while waiting for jobs to finish. Jobs started=%d, finishedSubtask=%d", started.getCount(), finished.getCount()), e);
        }
    }
}

